<template>
    <div>
        <div>
            <!-- 判断是蜀门还是王者荣耀 -->
            <div class="new-king-top" :class="this.$route.query.gameName == 'shudoor' ? 'shumen': ''">
                <div class="goback p-20 fl" v-if="appTrueTit">
                    <!-- <span class="span-go-back color-fff f26" @click="goBack" onclick="javascript:history.go(-1)">返回</span> -->
                    <span class="span-go-back color-fff f26" onclick="javascript:history.go(-1)">返回</span>

                </div>
                <div class="king-share" @click="shareClick" v-if="appTrueTit"></div>
            </div>
        </div>
        <!--商品过滤条件-->
        <div class="new-king-nav" ref="indexNav" :class="{'nav-fixed': indexNavFixed, 'shumen':this.$route.query.gameName == 'shudoor'}">
            <ul class="clearfix">
                <!-- <li class="fl text-center f30" :style="getWidth()" v-for="item in tabList"  :class="{'listActive':item.id==liActive}" @click="kingSendRequest(item.id)">{{item.classDesc}}</li> -->
                <!-- 蜀门标题栏切换样式是active，王者荣耀是listActive -->
                <li class="fl text-center f30" :style="getWidth()" v-for="(item,index) in tabList" :class="{'listActive active':item.id==liActive}" @click="kingSendRequest(item.id)">{{item.classTitle}}</li>
            </ul>
        </div>
        <div  class="new-king-nav" v-if="indexNavFixed"><ul class="clearfix"><li class="fl text-center f30" :style="getWidth()" v-for="(item,index) in tabList" :class="{'listActive':item.id==liActive}" @click="kingSendRequest(item.id)">{{item.classTitle}}</li></ul></div>
        <!-- //商品列表 -->
        <!-- 判断是蜀门还是王者荣耀是蜀门就是bg-650000 -->
        <div class=" px-20 py-30 " :class="this.$route.query.gameName == 'shudoor' ? 'bg-650000': 'bg-101f32'">
            <div class="container border-radius  bg-fff">
                <ul>
                    <li class="px-30 pt-30" v-for="(item,i) in goodsList" @click='gameDetailedDescription(item.goodsUrl,item.goodsId)' v-if="item.goodsStatus==0">
                        <a href="javascript:void(0)">
                            <div class="goods-box border-bottom clearfix">
                                <div class="fl goods-img">
                                    <!-- <img src="~images/m_king_images/goods-img.png" alt="商品图片"> -->
                                    <img :src="getImg(item.goodsImgUrl)" alt="商品图片">
                                </div>
                                <div class="fl goods-detail">
                                    <p class="goods-title">
                                        <i class="hot-sell fl color-fff f24 mr-15 text-center" v-if="getTitle(item)">{{item.sub_title}}</i>
                                        <span class="color-333 f30">{{item.goodsName}}</span>
                                    </p>
                                    <p class="f28 color-333 goods-price">￥{{item.goodsPrice}}</p>
                                    <p class="f26 color-519ae5 goods-explain">{{item.goodsDesc | goodsfilterName}}</p>
                                </div>
                                <div class="to-right"></div>
                            </div>
                        </a>
                    </li>
                </ul>
                <!--下拉区-->
                <div class="get-more py-30 text-center " @click='footerSendDate' v-if="footerMore">
                    <span class="f30 color-333">查看更多</span>
                </div>
            </div>

            <!--向下刷新无商品时显示-->
            <!-- 判断是蜀门还是王者荣耀是蜀门就是fieldsetLegend，加颜色的样式 -->
            <fieldset class="more-empty mt-30 footer-fixed" v-if="!footerMore" :class="this.$route.query.gameName == 'shudoor' ? 'fieldsetLegend' : ''">
                <legend class="f28 px-10" align="center" :class="this.$route.query.gameName == 'shudoor' ? 'fieldset_legend' : ''">我是有底线的</legend>
            </fieldset>

        </div>

        <share></share>
    </div>
</template>
<script>
import { mapActions, mapGetters, mapState } from 'vuex'
import share from 'components/common/NewShare.vue' // 分享
import api from '../../../../api'
export default {
    data() {
        return {
            goodsList: [],
            goodsDesc: [],
            tabList: [],
            liActive: 3,
            mapList: {},
            footerMore: true,
            indexNavFixed: false,
            goodsType:'',
            appTrueTit:(this.$route.query.app ? false : true),
            UserInfo: {},
            isLogin: false
        }
    },
    components: {
        share
    },
    created() {
        api.seller.queryCurrentUserInfo().then(res => {  // 做蜀门活动数据埋点
            if (res && res.body.success) {
                this.isLogin = true
                this.UserInfo = res.body.userInfo
                this.$http.post('/api/mobile-topic-service/rs/activityUser/createActivityUser',{ // 蜀门活动用户注册/登录的数据埋点
                    userId: this.UserInfo.pcUserId,
                    userMobile: this.UserInfo.mobilePhone,
                    userRegTime: this.UserInfo.createTime,
                    tjType: '登录',
                    activityType: '蜀门手游专区'
	     })
            } else {
                this.isLogin = false
                this.UserInfo = {}
            }
            if (this.isLogin && this.$route.query.key == 'activity') {  // 创建用户分享的数据埋点
                this.$http.post('/api/mobile-topic-service/rs/activityShare/createActivityShare', {
                    shareUserId: this.$route.query.userId,    // 分享用户ID
                    beshareUserId: this.UserInfo.pcUserId,  // 被分享用户ID
                    besharePhone: this.UserInfo.mobilePhone,   // 被分享用户手机号
                    beshareRegTime: this.UserInfo.createTime, // 被分享用户注册时间
                    activityType: '蜀门手游专区'
                })
            }
            this.shareUrlLink()
            if (this.$route.query.gameName == 'shudoor') {
                document.title = '【5173】蜀门手游专区'
                if (this.isLogin) {
                    if (location.href.indexOf('key') > -1) {
                        console.log(window.location.origin,'lal ')
                        if (this.UserInfo.pcUserId !== this.$route.query.userId) {
                            location.href = location.href.split('&')[0] + '&key=activity&userId=' + this.UserInfo.pcUserId;
                        }
                    } else {
                        location.href = location.href.split('&')[0] + '&key=activity&userId=' + this.UserInfo.pcUserId;
                    }
                }
            }
        });
     },
     mounted(e) {

     },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            vm.fromName = from.name || 'list'
            vm.init()
        })
    },
    beforeDestroy() {
        let save = {
            mapList: this.mapList,
            page: this.page,
            liActive: this.liActive,
            tabList: this.tabList,
            footerMore: this.footerMore,
            goodsList: this.goodsList,
            indexNavFixed: this.indexNavFixed,
            scrollTop: this.scrollTop
        }
        this.$store.commit('saveSpData', save)
        window.removeEventListener('scroll', this.scroll) // 销毁滚动监听
    },
    methods: {
        shareUrlLink () {
            /*
            * 分享数据，可选参数
            * url, 分享的链接，如果不传则会自动获取浏览器地址
            * title, 分享的标题
            * summary, 分享的简介
            */
            let shareUrl;
            if (this.$route.query.gameName == 'shudoor') { // 判断是不是蜀门手游还是王者荣耀
                this.$bus.emit('busShareQZone',{
                    title: '5173蜀门手游专区',
                    url: encodeURIComponent(location.href),
                    summary: '5173蜀门手游专区',
                })
                shareUrl = window.location.origin + '/vue/special/' + this.$route.params.id + '?gameName=' + this.$route.query.gameName +'&key=activity&userId=' + this.UserInfo.pcUserId
                this.$bus.emit('urlAddress', `5173蜀门手游专区 ${shareUrl}`)
            } else if (this.$route.query.gameName == '王者荣耀') {
                this.$bus.emit('busShareQZone',{
                    title: '5173王者荣耀专区',
                    url: encodeURIComponent(location.href),
                    summary: '5173王者荣耀专区',
                })
            }
        },
        shareClick() {
            /*
            * 分享数据，可选参数
            * url, 分享的链接，如果不传则会自动获取浏览器地址
            * title, 分享的标题
            * summary, 分享的简介
            */
            this.shareStatus = true
            this.moreStatus = false
            this.$bus.emit('shareShow', this.shareStatus)
            this.$bus.emit('busShareUrl', window.location.href)
        },
        init() {
            this.saveSpData = this.$store.state.mobileGame.saveSpData
            /* 所有初始化需要的数据，或是需要执行的方法 放置在此处 */
            this.$store.commit('clearsaveSpData')
            /* 回归数据 */
            if (this.saveSpData && (this.fromName === 'MGAccountDetail' || this.fromName === 'MGAccountDetailNew')) {
                for (let key in this.saveSpData) {
                    this[key] = this.saveSpData[key]
                }
                this.$nextTick(function() {
                    let self = this
                    setTimeout(function() {
                        document.body.scrollTop = Number(self.saveSpData.scrollTop)
                    }, 1)
                })
            } else {
                this.initAjax();
            }
            this.indexNavTop = Number(this.$refs.indexNav.offsetTop) // 获取菜单栏离屏幕顶部的距离
            window.addEventListener('scroll', this.scroll);
        },
        getTitle(item) {
            let title = false;
            if (item.goodsDesc) {
                item.sub_title = item.goodsDesc.match(/【(\S*)】/);
                if (item.sub_title) {
                    item.sub_title = item.sub_title[1]
                    title = true
                }
            }
            return title
        },
        getImg(goodsImgUrl) {
            if (!goodsImgUrl) {
                goodsImgUrl = '/dist/default_img.jpg?3b979244708bc68974bb6499a05169b4'
            }
            return goodsImgUrl
        },
        /* 滚动监听 */
        scroll() {
            if (document.body.scrollTop >this.indexNavTop) {
                if (!this.indexNavFixed) this.indexNavFixed = true
            } else {
                if (this.indexNavFixed) this.indexNavFixed = false
            }
            this.scrollTop = document.body.scrollTop
        },
        getWidth() {
            let self = this;
            let width = 100 / self.tabList.length;
            return 'width:' + width + '%'
        },
        kingSendRequest(classId) {
            let self = this;
            self.mapList[self.liActive] = {}
            self.mapList[self.liActive].list = self.goodsList
            self.mapList[self.liActive].page = self.page
            self.mapList[self.liActive].footerMore = self.footerMore
            if (self.mapList[classId]) {
                self.goodsList = []
                setTimeout(function () {
                self.goodsList = self.mapList[classId].list;
                self.footerMore = self.mapList[classId].footerMore;
                self.page = self.mapList[classId].page;
        　　　　}, 10);
            } else {
                self.footerMore = true
                self.goodsList = [];
                self.getList(classId, 1);
            }
            self.liActive = classId;

        },

        gameDetailedDescription(goodsUrl, goodsId) {//点击跳转到详细信息
            if (!this.isLogin) { // 先判断有没有登录，如果没有登录先到登录见面去  wangjun
                if (this.$route.query.key == 'activity') { // 判断有没有登录
                    location.href = `/vue/login?returnUrl=${encodeURIComponent(location.origin + '/vue/special/'+ this.$route.params.id + '?gameName=' + this.$route.query.gameName +'&key=activity&userId=' + this.$route.query.userId)}`
                } else {
                    location.href = '/vue/login?returnUrl='+ location.origin +'/vue/special/' + this.$route.params.id + '?gameName=' + this.$route.query.gameName 
                }
            } else {
            if (goodsUrl.indexOf(location.hostname) > 0&&!this.$route.query.app) {
            	var type = 0
            	if(goodsId[0]!='M'){
		            type = 1
                }
                // 注释保留 2018.4.1 yanjd@0.0.2
                // this.$router.push({
                //     name: 'MGAccountDetail',
                //     params: {
                //         goodsId: goodsId,
                //         goods_source_type:type
                //     }
                // })
                if (type == 1) {
                    this.$router.push({
                        name: 'MGAccountDetailNew',
                        params: {
                            goodsId: goodsId,
                            goods_source_type:type
                        }
                    })
                } else {
                    this.$router.push({
                        name: 'MGAccountDetail',
                        params: {
                            goodsId: goodsId,
                            goods_source_type:type
                        }
                    })
                }
            } else {
	            if(goodsUrl.indexOf('?')>-1){
                        if (this.$route.query.gameName = 'shudoor') {
                            goodsUrl = this.$route.query.app?goodsUrl+'&app='+this.$route.query.app:goodsUrl + '&channelId=a_openAccount_20180118001'
                        } else {
		            goodsUrl = this.$route.query.app?goodsUrl+'&app='+this.$route.query.app:goodsUrl
                        }
	            }else{
                        if (this.$route.query.gameName = 'shudoor') {
                            goodsUrl = this.$route.query.app?goodsUrl+'?app='+this.$route.query.app:goodsUrl + '&channelId=a_openAccount_20180118001'
                        } else {
		            goodsUrl = this.$route.query.app?goodsUrl+'?app='+this.$route.query.app:goodsUrl
	            }
                    }
                location.href = goodsUrl
            }
            }

        },
        initAjax() {
            let self = this;
            let params = { topicId: self.$route.params.id }
            self['MG_GET_FIRST_KING_LIST'](params).then(res => {
                self.tabList = res
                self.liActive = res[0].id;
                self.getList(res[0].id);//初始页面调用ajax
            })
        },
        getList(goodsType, page) {
            var self = this
            page = page || 1;
            self.page = page
//            self.goodsType = goodsType
            let params = {
                classId: goodsType, pageSize: 10, page: page
            }
            if (self.footerMore) {
                self['MG_GET_KING_LIST'](params).then(list => {
                    if (page == 1 && list) {
                        self.goodsList = list;
                    } else if (list) {
                        self.goodsList = this.goodsList.concat(list);
                    }
                    if ((list && list.length < 10) || !list) {
                        self.footerMore = false
                    }
                })
            }
        },

        footerSendDate() {
            this.page++;
            this.getList(this.liActive, this.page)
        },
        ...mapActions(['MG_GET_KING_LIST', 'MG_GET_FIRST_KING_LIST']) // 获取商品列表（所有）
    },
    filters: {
        goodsfilterName(str) {
            let strStart = str.indexOf('【');
            if (str.indexOf('【') == 0) {
                return (str.substring(str.indexOf('】') + 1, str.length));
            } else {
                return (str.substring(0, strStart) + str.substring(str.indexOf('】') + 1, str.length))
            }
        }
    }
}
</script>
<style scoped>
.bg-101f32 {
    background: #101f32
}

.listActive {
    line-height: 0.9rem;
    color: #75b9ff;
    background: #101f32;
    border-bottom: none;
    border-top: 0.06rem solid #519ae5;
}

.nav-fixed {
    width: 100%;
    position: fixed;
    top: 0;
    z-index: 99;
}

.goods-img {
    width: 1.3rem;
}
/* wangjun  样式添加 */
.fieldset_legend {
    color: #f8e09e;
}
.fieldsetLegend {
    border-top: 1px solid #f8e09e;
}
</style>
<style src="css/mobgame/king-special.css"></style>
